<?php

/**
 * Description of Application_Model_Local
 *
 * @author Jean Brito
 */
class Application_Model_Local {

	static public function index($model, $filter = null, $start = null, $limit = null, $sort = null) {
		$sql = "select ".self::getSqlSelect($model)." from " . $model->getTableName()." ".self::getSqlWhere($model,$filter)." ".self::getSqlOrderBy($model,$sort);
		$db = Zend_Db_Table::getDefaultAdapter();
		try {
			$rows = $db->fetchAll($sql);
			return array('success' => true, 'data' => $rows, 'total' => count($rows),'message'=>'Registros lidos com sucesso');
		} catch (Zend_Db_Exception $error_string) {
			if(Application_Model_Local::CheckDbException($error_string, $model)){
				return self::index($model, $filter, $start, $limit, $sort);
			}
			return array('success' => false, 'message' => $error_string->getMessage(),'total'=>0,'data'=>array());
		}
		return array();
	}

	static public function get($model, $id) {
		$result=self::index($model,array(array('property'=>'id','value'=>$id)));
		if(isset($result['data'][0]))$result['data']=$result['data'][0];
		return $result;
	}

	static public function post($model, $data) {
		$fields='';$values='';
		foreach ($model->getFields() as $setup) {
			$field=$setup['name'];
			if(isset($model->{$field})){
				$value=$model->{$field}->getSqlSet(isset($data[$field])?$data[$field]:null);
				if($value!=null){
					$fields.=",".$model->{$field}->getSqlFieldName();
					$values.=",".$value;
				}
			}
		}
		$fields=substr($fields,1,strlen($fields));
		$values=substr($values,1,strlen($values));

		$sql = "insert into " . $model->getTableName() . " ($fields) values ($values)";

		$db = Zend_Db_Table::getDefaultAdapter();
		try {
			$db->query($sql);
			$id=$db->lastInsertId();
			$data=self::get($model,$id);
			return array('success' => true, 'message' => 'registro inserido com sucesso','data'=>$data['data'],'total'=>1);
		} catch (Zend_Db_Exception $error_string) {
			Application_Model_Local::CheckDbException($error_string, $model);
			return array('success' => false, 'message' => $error_string->getMessage());
		}
		return array();
	}

	static public function delete($model, $id) {
		$sql = "delete from " . $model->getTableName() . " where id='$id'";
		$db = Zend_Db_Table::getDefaultAdapter();
		try {
			$db->query($sql);
			return array('success' => true, 'message' => 'registro inserido com sucesso', 'data'=>array());
		} catch (Zend_Db_Exception $error_string) {
			Application_Model_Local::CheckDbException($error_string, $this);
			return array('success' => false, 'message' => $error_string->getMessage());
		}
		return array();
	}

	static public function put($model,$id, $data) {
		$filter=Array(Array('property'=>'id','value'=>$id));
		$sets='';
		foreach ($model->getFields() as $setup) {
			$field=$setup['name'];
			if(isset($model->{$field})){
				$value=$model->{$field}->getSqlSet(isset($data[$field])?$data[$field]:null);
				if($value!=null){
					$sets.=",".$model->{$field}->getSqlFieldName()."=".$value;
				}
			}
		}
		$sets=substr($sets,1,strlen($sets));
		$sql = "update " . $model->getTableName() . " set $sets ".self::getSqlWhere($model,$filter);
		if($model->debug)print $sql;

		$db = Zend_Db_Table::getDefaultAdapter();
		try {
			$db->query($sql);
			$data=self::index($model,Array(Array('property'=>'id','value'=>$id)));
			return array('success' => true, 'message' => 'registro atualizado com sucesso' ,'data'=>(isset($data['data'][0])?$data['data'][0]:array()),'total'=>1);
		} catch (Zend_Db_Exception $error_string) {
			Application_Model_Local::CheckDbException($error_string, $this);
			return array('success' => false, 'message' => $error_string->getMessage());
		}
		return array();
	}


	static public function getSqlSelect($model) {
		$fields="";
		foreach($model->getFields() as $field)
			$fields.=",".$model->{$field['name']}->getSqlSelect();
		if($fields!="")$fields=substr($fields,1,strlen($fields));else $fields="*";
		return $fields;
	}
	static public function getSqlWhere($model, $filter = null) {
		$orderby="";
		if(count($filter))foreach($filter as $fil){
			$field=$fil['property'];
			if(isset($model->{$field}))
				$orderby.="and ".$model->{$field}->getSqlWhere($fil['value']);
		}
		if($orderby!="")$orderby="where ".substr($orderby,4,strlen($orderby));
		return $orderby;
	}
	static public function getSqlOrderBy($model, $sort = null) {
		return "";
	}

	static public function CheckDbException(Zend_Db_Exception $error, Application_Model_Abstract $model) {
		/*
		 * [0] => 42S02
		* [1] => 1146
		* [2] => Table 'agentenet.utilitario_modulo' doesn't exist
		*/
		if ($error->getPrevious()->errorInfo[0] == '42S02') {
			return self::createSqlTable($model);
		}
		/*
		 * [0] => 42S22
		* [1] => 1054
		* [2] => Unknown column 'titulo' in 'field list'
		*/
		if ($error->getPrevious()->errorInfo[0] == '42S22') {
			$field=explode("'",$error->getPrevious()->errorInfo[2]);
			$field=$field[1];
			return self::createSqlAddField($model,$field);
		}
		return false;
	}

	static public function createSqlAddField($model,$field){
		$create="alter table ".$model->getTableName()." add ".$model->{$field}->getSqlCreate();
		$db = Zend_Db_Table::getDefaultAdapter();
		try {
			$db->query($create);
			return true;
		} catch (Zend_Db_Exception $error_string) {
			Application_Model_Local::CheckDbException($error_string, $model);
			echo array('success' => false, 'message' => $error_string->getMessage());
			exit;
		}
	}
	static public function createSqlTable($model){

		$create="create table ".$model->getTableName()." (" ;
		foreach($model->getFields() as $field)
			$create.=$model->{$field['name']}->getSqlCreate().",";
		$create=substr($create,0,strlen($create)-1).")";

		$db = Zend_Db_Table::getDefaultAdapter();
		try {
			$db->query($create);
			return true;
		} catch (Zend_Db_Exception $error_string) {
			Application_Model_Local::CheckDbException($error_string, $model);
			echo array('success' => false, 'message' => $error_string->getMessage());
			exit;
		}
	}

}
